package config

import (
	"fmt"
	"gopkg.in/mgo.v2"
	"strings"
	"time"
)

var MgDb *mgo.Session

func MgInit() {
	MgDb = MgConn(GConfig.MongoDB)
	CkeckMgActive()
}

func MgConn(value Config_mg) *mgo.Session {
	// 创建连接
	session, errss := mgo.DialWithTimeout(value.Addr, time.Duration(value.TimeOut)*time.Second)
	if errss != nil {
		panic("创建连接失败: " + errss.Error())
		return nil
	}
	// 设置用户凭证
	if err := session.Login(&mgo.Credential{
		Username:  value.UserName,
		Password:  value.Passport,
		Mechanism: "SCRAM-SHA-1",
	}); err != nil {
		panic("登录失败: " + err.Error())
		return nil
	}
	session.SetPoolLimit(1000)
	errs := session.Ping()
	if errs != nil {
		panic("mg ping is err:" + errs.Error())
	}
	return session
}

func CkeckMgActive() {
	go func() {
		i := 1
		for range time.NewTicker(time.Second * time.Duration(1)).C {
			if i == 5 {
				panic("mg数据库链接被重置，重启服务: ")
				return
			}
			errs := MgDb.Ping()
			if errs != nil {
				if strings.Contains(errs.Error(), " i/o timeout") || strings.Contains(errs.Error(), " EOF") {
					fmt.Println("数据库链接被重置，重新链接: " + errs.Error())
					MgDb = MgConn(GConfig.MongoDB)
					i++
					//panic("数据库链接被重置，重启服务: " + errs.Error())
				} else {
					fmt.Println("mongodb is error: " + errs.Error())
				}
			}
		}
	}()
}
